/* 

http://creativepark.net/blog/entry/id/1191
http://www.html5rocks.com/tutorials/#webdatabase

*/

package nl.stroep.db 
{
	import flash.display.Sprite;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.external.ExternalInterface;
	import flash.utils.Dictionary;
	import nl.stroep.html.HTML;
	import nl.stroep.utils.Logger;
	
	/**
	 * ...
	 * @author Mark Knol
	 */
	public class Database 
	{
		public var console:Logger = new Logger();
		public var html:HTML = new HTML();
		
		public var name:String;
		public var version:String;
		public var description:String;
		public var size:Number;
		
		public var queue:Array = []
		
		public function Database(name:String, version:String = "1.0", description:String = "", size:Number = 1048576 ) 
		{
			this.name = name;
			this.version = version;
			this.description = description;
			this.size = size;
			
			if (available)
			{
				ExternalInterface.addCallback("onDatabaseCallSucces", onDatabaseCallComplete);
				ExternalInterface.addCallback("onDatabaseCallFailed", onDatabaseCallFailed);
			}
		}
		
		private function onDatabaseCallFailed(tx:*,result:*):void
		{
			callQueue();
			console.log( "onDatabaseCallFailed", tx, Logger.getObject(result) );
		}
		
		private function onDatabaseCallComplete(tx:*, result:*):void
		{
			callQueue();
			console.log( "onDatabaseCallComplete", tx, Logger.getObject(result) );
		}
		
		public function createDatabase():void
		{
			if (available) 
			{
				if (html.window.openDatabase)
				{
					queue.push ( function():void { html.callFunction("createDatabase", name, version, description, size); } );
					callQueue();
					console.log("Succes creating database:", "\n\tname:", name, "\n\tversion:", version, "\n\tdescription:", description, "\n\tsize:", size);
					
				}
				else
				{
					console.log("Failed window.openDatabase");
				}
			}
		}
		
		public function createTable( table:Table ):void
		{
			if (available)
			{
				var query:String = "CREATE TABLE IF NOT EXISTS " +  table.name + "(" + table.toString() + ")";
				
				executeQuery(name, query);
			}
		}
		
		//tx.executeSql('INSERT INTO todo(todo, added_on) VALUES (?,?)', 
		public function insertRow( tableName:String, fields:Array, values:Array):void
		{
			if (available)
			{
				var query:String = "INSERT INTO " + tableName + " (" + fields + ") VALUES (" + getQuestionMarks(fields) + ")";
				
				executeQuery(name, query, values);
			}
		}
		
		private function getQuestionMarks(fields:Array=null):String
		{
			var retval:String = "";
			for (var i:uint = 0; i < fields.length; ++i) 
			{
				retval += "?";
				if (i != fields.length - 1) retval += ",";
			}
			return retval
		}
		
		public function dropTable( tableName:String):void
		{
			if (available)
			{
				var query:String = "DROP TABLE IF EXISTS " +  tableName;
				
				executeQuery(name, query);
			}
		}
		
		public function executeQuery(name:String, query:String, variables:Array = null):void
		{
			if (available)
			{
				queue.push( function():void { html.callFunction("executeQuery", name, query, variables) } );
				/*if (queue.length == 1)
				{
					callQueue();
				}*/
				/*
				if (variables)
				{
					html.callFunction("executeQuery", name, query, variables);
				}
				else
				{
					html.callFunction("executeQuery", name, query);
				}*/
			}
		}
		
		private function callQueue():void
		{
			console.log("try call Queue");
			if (queue.length > 0)
			{
				console.log("callQueue: ", queue[0]);
				this[queue.shift()]();
			}
			
		}
		
		public function get available():Boolean 
		{ 
			if (!ExternalInterface.available) 
			{
				console.log("ExternalInterface not available"); 
				return false;
			}
			
			/*f (!html.window.dbUtil)
			{
				console.log("No dbUtil found");
				return false;
			}*/
			
			return true;
		}
		
	}

}